package com.sword.erp.order.interfaces.api;

import com.sword.erp.logistics.service.LogisticsOverseasService;
import com.sword.erp.logistics.service.dto.LogisticsRequest;
import com.sword.erp.order.feignclient.LogisticsService;
import com.sword.erp.order.feignclient.StockService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.time.Instant;

/**
 * 订单接口
 * @author sword
 * @date 2021/10/10 14:11
 */
@RefreshScope
@RestController
@Slf4j
@RequiredArgsConstructor
public class OrderApi {
    /**
     * RestTemplate
     */
    private final RestTemplate restTemplate;

    private final LogisticsService logisticsService;

    private final StockService stockService;

    @DubboReference(version = "1.0", group = "LogisticsGroup", interfaceClass = LogisticsOverseasService.class,
            mock = "com.sword.erp.logistics.service.mock.LogisticsOverseasServiceMock", check = false)
    private LogisticsOverseasService logisticsOverseasService;

    @Value("${app.user.name:sword}")
    private String userName;

    /**
     * 创建订单
     * @return java.lang.String
     * @author sword
     * @date 2021/10/10 14:13
     */
    @PostMapping("/rest")
    public String createOrderRest() {
        log.info("创建订单成功，订单号为{}", Instant.now().toString());
        restTemplate.getForObject("http://stock/stock/reduce", String.class);
        restTemplate.getForObject("http://logistics/logistics", String.class);
        return "success";
    }

    /**
     * 创建订单
     * @return java.lang.String
     * @author sword
     * @date 2021/10/10 14:13
     */
    @PostMapping("/feign")
    public String createOrderFeign() {
        log.info("{}创建订单成功，订单号为{}", userName, Instant.now().toString());
        stockService.reduceStock();
        logisticsService.createLogistics();
        return "success";
    }

    /**
     * 创建海外订单
     * @return java.lang.String
     * @author sword
     * @date 2021/10/10 14:13
     */
    @PostMapping("overseas/feign")
    public String createOverseasOrderFeign() {
        String orderCode = Instant.now().toString();
        log.info("{}创建海外订单成功，订单号为{}", userName, orderCode);
        stockService.reduceStock();
        logisticsOverseasService.createOverseasLogistics(LogisticsRequest.builder().orderCode(orderCode).build());
        return "success";
    }
}
